package com.top145;

public class Solution138 {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Node dummy = new Node(0);
        dummy.next = head;
        Node p = head;
        while (p != null) {
            Node tmp = new Node(p.val);
            tmp.next = p.next;
            p.next = tmp;
            p = tmp.next;
        }
        p = head;
        while (p != null) {
            if (p.random == null) p.next.random = null;
            else {
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }
        dummy.next = head.next;
        p = head.next;
        Node n;
        Node pre = head;
        while (p.next != null && p.next.next != null) {
            n = p.next.next;
            pre.next = p.next;
            p.next = n;
            p = n;
            pre = pre.next;
        }
        pre.next = null;
        return dummy.next;
    }
}

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}